package com.gyx.lottery.dao.handler;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.gyx.lottery.dao.dataobject.Encrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes(Encrypt.class)//要处理的类型
@MappedJdbcTypes(JdbcType.VARCHAR)//转化的类型
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {
    //设置密钥
    private static final byte[] KEY="111222333444555P".getBytes(StandardCharsets.UTF_8);

    /**
     *
     * @param ps SQL 预编译对象
     * @param i 需要赋值的索引位置
     * @param parameter 原本I位置需要赋参数
     * @param jdbcType jdbc类型
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
        if(null==parameter||null==parameter.getValue()){
            ps.setString(i,null);
            return ; }
        AES aes= SecureUtil.aes(KEY);
        String str=aes.encryptHex(parameter.getValue());
        ps.setString(i,str);


    }

    /**
     *
     * @param rs 结果集
     * @param columnName 列名
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
        System.out.println("getNullableResult获得的加密内容为:"+rs.getString(columnName));
        return decrpt(rs.getString(columnName));
    }

    @Override
    public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        System.out.println("getNullableResult:获得的加密内容为"+rs.getString(columnIndex));
        return decrpt(rs.getString(columnIndex));
    }

    @Override
    public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        System.out.println("CallableStatement获得的加密内容为:"+cs.getString(columnIndex));
        return decrpt(cs.getString(columnIndex));
    }
    private Encrypt decrpt(String str){
        //进行解密
        return new Encrypt(SecureUtil.aes(KEY).decryptStr(str));
    }
}
